<template>
  <a-spin :spinning="spinning" tip="发布成功，正在跳转页面...">
    <paper-top :paper="paper" isType="add" @changeTitle="changeTitle" @changeStatus="changeStatus" @changeStartTime="changeStartTime" @changeEndTime="changeEndTime" />
    <div v-for="(questionsItem, index) in paper.questions" :key="index" class="content">
      <questions-item :index="index" :questionsItem="questionsItem" :itemLength="paper.questions.length" @addQuestion="addQuestion" @deleteQuestion="deleteQuestion" />
    </div>
    <div class="bottom">
      <a-button type="primary" size="large" @click="publishPaper" block style="height: 40px; margin: 0 20px; width: 97%">新增问卷</a-button>
    </div>
  </a-spin>
</template>

<script lang="ts">
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode, defineComponent, ref, toRaw, reactive } from 'vue'
import PaperTop from '../../../components/paperTop.vue'
import QuestionsItem from '../../../components/questionSetting.vue'
import { useRouter } from 'vue-router'
import { Modal, message } from 'ant-design-vue'
import { post } from '../../../utils/request/request'
import 'ant-design-vue/es/message/style/css'

interface PaperData {
  title: string
  start_time: string
  end_time: string
  status: number
  questions: {
    number: number | undefined
    is_require: boolean
    questionType: number
    questionTitle: string
    questionOption: string[] | never[]
  }[]
}

interface QuestionsItems {
  number: number | undefined
  is_require: boolean
  questionType: number
  questionTitle: string
  questionOption: string[] | never[]
}

const useChangeEffect = (paper: PaperData) => {
  const changeTitle = (title: string) => {
    paper.title = title
  }
  const changeStatus = (status: number) => {
    paper.status = status
  }
  const changeStartTime = (start_time: string) => {
    paper.start_time = start_time
  }
  const changeEndTime = (end_time: string) => {
    paper.end_time = end_time
  }
  return {
    changeTitle,
    changeStatus,
    changeStartTime,
    changeEndTime
  }
}

// 增删组件相关逻辑
const useEmitEffect = (paper: PaperData) => {
  const addQuestion = (index: number) => {
    const newItem: QuestionsItems = {
      number: undefined, //题号
      is_require: true, //是否必填
      questionType: 1, //问题类型：1.单选题 2.多选题 3.填空题
      questionTitle: '', //问题描述
      questionOption: ['', ''] //问题选项，填空题无元素，选择题必须包含两个以上元素
    }
    paper.questions.splice(index + 1, 0, newItem)
  }
  const deleteQuestion = (index: number) => {
    console.log(index)
    paper.questions.splice(index, 1)
  }
  return {
    addQuestion,
    deleteQuestion
  }
}

//问卷相关逻辑
const usePaperEffect = (token: string) => {
  const router = useRouter()
  const spinning = ref(false)
  const paper: PaperData = reactive({
    title: '', //问卷标题
    start_time: '', //开始时间
    end_time: '', //截止时间
    status: 0, //状态
    questions: [
      {
        number: undefined, //题号
        is_require: true, //是否必填
        questionType: 1, //问题类型：1.单选题 2.多选题 3.填空题
        questionTitle: '', //问题描述
        questionOption: ['', ''] //问题选项，填空题无元素，选择题必须包含两个以上元素
      }
    ]
  })
  const publishPaper = () => {
    paper.questions.forEach((questionsItem, index) => {
      questionsItem.number = index + 1
    })
    let isFilled = false
    console.log(paper.title, paper.start_time, paper.end_time)
    if (paper.title && paper.start_time && paper.end_time) {
      paper.questions.forEach((item) => {
        if (item.number && item.questionType && item.questionTitle) {
          isFilled = item.questionOption.every((option) => option !== '')
        } else {
          isFilled = false
        }
      })
    } else {
      isFilled = false
    }
    if (isFilled) {
      Modal.confirm({
        title: '你确定问卷内容无误?',
        icon: createVNode(ExclamationCircleOutlined),
        async onOk() {
          const res: any = await post('/admin/api/v1/paper', toRaw(paper), token)
          if (res.code === 0) {
            console.log(toRaw(paper))
            spinning.value = !spinning.value
            setTimeout(() => {
              spinning.value = !spinning.value
              router.push({ name: 'paperList' })
            }, 1000)
          } else {
            message.error('添加失败')
          }
        }
      })
    } else {
      message.warn('问卷相关信息未编辑完成')
    }

    console.log(isFilled)
  }

  return { spinning, paper, publishPaper }
}

export default defineComponent({
  components: {
    PaperTop,
    QuestionsItem
  },
  setup() {
    const token = localStorage.getItem('token') as string

    const { spinning, paper, publishPaper } = usePaperEffect(token)
    const { changeTitle, changeStatus, changeStartTime, changeEndTime } = useChangeEffect(paper)
    const { addQuestion, deleteQuestion } = useEmitEffect(paper)

    return {
      paper,
      publishPaper,
      spinning,
      changeTitle,
      changeStatus,
      changeStartTime,
      changeEndTime,
      addQuestion,
      deleteQuestion
    }
  }
})
</script>

<style lang="less" scoped>
.content {
  padding: 20px 20px 0 20px;
}
</style>
